package controller

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"parking-lot-go-push/config"
)

// curl 请求
func CurlPostJson(url string, jsonData map[string]interface{}) (err error) {

	//推送url前缀
	dbSection := config.Cfg.Section("SYSTEM")
	dingTalkPushUrl := dbSection.Key("DINGTALK_PUSH_URL").String()
	url = dingTalkPushUrl + url
	fmt.Println(url)
	// 将 JSON 数据封装为请求体
	jsonBytes, err := json.Marshal(jsonData)
	if err != nil {
		return errors.New("转换json失败")
	}

	// 创建自定义的 HTTP 客户端
	client := &http.Client{}

	// 创建 POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes))
	if err != nil {
		return errors.New("创建请求失败")
	}

	req.Header.Set("Content-Type", "application/json; charset=utf-8")

	// 发起请求
	response, err := client.Do(req)

	if err != nil {
		return errors.New("请求失败")
	}

	defer response.Body.Close()

	// 读取响应内容
	responseBody, err := io.ReadAll(response.Body)
	if err != nil {
		return errors.New("获取响应内容失败")
	}

	fmt.Println(string(responseBody))
	return nil
}
